﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.DataAccess;
using YiYiTong.Rocket.EFDBFirst;
using System.Text.RegularExpressions;

namespace YiYiTong.Rocket.Business
{
    public class PushMsgBiz
    {
        #region 单例模式
        private PushMsgBiz()
        {
        }

        private static PushMsgBiz _instance;
        private static readonly object _syncObject = new object();

        public static PushMsgBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new PushMsgBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式

        #region 个人消息
        /// <summary>
        /// 个人消息列表
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, PushMsgListModel> GetPushMsgList(long uid, int msgtype, int pageIndex, int pageRows)
        {
            DataSet ds = PushMsgDataAccess.Instance.GetPushMsgList(uid, msgtype, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                PushMsgListModel model = new PushMsgListModel();
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);
                model.notReadRows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["notReadRows"]);
                model.list = new ModelHandler<PushMsgModel>().FillModel(ds.Tables[1]);

                return new Tuple<bool, PushMsgListModel>(true, model);
            }
            else
                return new Tuple<bool, PushMsgListModel>(false, null);
        }


        /// <summary>
        /// 设置消息已读
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="msgid"> =0表示设置所有消息已读 >0 表示单个消息已读</param>
        /// <returns></returns>
        public Tuple<bool, string> ReadPushMsg(long uid, long msgid)
        {
            PushMsgDataAccess.Instance.ReadPushMsg(uid, msgid);

            return new Tuple<bool, string>(true, "设置已读成功");
        }

        public Tuple<bool, string> AddPushMsg(AddPushMsgModel paramModel)
        {
            Utils.Trim(paramModel);
            long id = paramModel.aDZ_Pushmessage.ID;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (id > 0)
            {
                var old_model = dbcontext.ADZ_Pushmessage.FirstOrDefault(t => t.ID == id);
                if (old_model != null)
                {
                    old_model.Sender = paramModel.aDZ_Pushmessage.Sender;
                    old_model.MsgTitle = paramModel.aDZ_Pushmessage.MsgTitle;
                    old_model.MsgText = paramModel.aDZ_Pushmessage.MsgText;
                }
                dbcontext.SaveChanges();
            }
            else
            {
                paramModel.aDZ_Pushmessage.CreateTime = DateTime.Now;
                paramModel.aDZ_Pushmessage.ImgUrl = "";
                paramModel.aDZ_Pushmessage.IsAllRead = 0;
                paramModel.aDZ_Pushmessage.IsShow = 1;
                paramModel.aDZ_Pushmessage.MsgStatus = 0;
                paramModel.aDZ_Pushmessage.Sender = paramModel.aDZ_Pushmessage.Sender;
                paramModel.aDZ_Pushmessage.SortID = 0;
                paramModel.aDZ_Pushmessage.UrlAddress = "";
                paramModel.aDZ_Pushmessage.UrlName = "";

                dbcontext.ADZ_Pushmessage.Add(paramModel.aDZ_Pushmessage);
                dbcontext.SaveChanges();
                long msgid = paramModel.aDZ_Pushmessage.ID;

                if (paramModel.aDZ_Pushmessage.ReceiveType == 1)
                {
                    string[] uidarr = Regex.Split(paramModel.ReceiveUids, ",");
                    for (int i = 0; i < uidarr.Length; i++)
                    {
                        long uid = ConvertHelper.TryPraseLong(uidarr[i], 0);
                        if (uid > 0)
                        {
                            ADZ_PushmsgIsread isread = new ADZ_PushmsgIsread
                            {
                                CreateTime = DateTime.Now,
                                IsRead = 0,
                                MsgID = msgid,
                                UID = uid
                            };
                            dbcontext.ADZ_PushmsgIsread.Add(isread);
                        }
                    }
                    dbcontext.SaveChanges();
                }
            }
            return new Tuple<bool, string>(true, "操作成功");
        }

        /// <summary>
        /// 推送绑定设备
        /// </summary>
        /// <returns></returns>
        public bool BindMemberPush(long uid, string device_token, int device_type)
        {
            if (uid < 0 || string.IsNullOrWhiteSpace(device_token))
                return false;

            string stroutput = string.Empty;
            long ret = PushMsgDataAccess.Instance.BindMemberPush(uid, device_token, device_type, out stroutput);
            if (ret > 0)
                return true;
            else
                return false;
        }

        public PushMessageRequest GetPushMsgReq(ADZ_MasterEntities dbcontext, ADZ_Pushmessage pushmsg)
        {
            var data = new
            {
                imgurl = string.IsNullOrEmpty(pushmsg.ImgUrl) ? "" : pushmsg.ImgUrl,
                msgid = pushmsg.ID

            };
            PushMessageRequest request = new PushMessageRequest();
            request.Alert = pushmsg.MsgText;
            request.DeviceType = 1;
            request.Title = pushmsg.MsgTitle;
            request.Text = JsonHelper.Serialize(data);
            request.MsgType = pushmsg.MsgType;

            if (pushmsg.ReceiveType == 0)
                request.PushType = 1;
            else
            {
                //针对用户推送
                string deviceTokes = "";
                var pushUser = dbcontext.ADZ_PushmsgIsread.FirstOrDefault(t => t.MsgID == pushmsg.ID);
                if (pushUser != null)
                {
                    //获取用户绑定的设备
                    var memberPushList = dbcontext.ADZ_MemberPushMsg.Where(t => t.uid == pushUser.UID).ToList();
                    if (memberPushList != null && memberPushList.Count != 0)
                    {
                        foreach (var item in memberPushList)
                            deviceTokes += item.device_token + ",";
                    }

                    if (!string.IsNullOrEmpty(deviceTokes) && deviceTokes.EndsWith(","))
                        deviceTokes = deviceTokes.Substring(0, deviceTokes.Length - 1);
                }

                if (string.IsNullOrEmpty(deviceTokes))
                {
                    LogHelper.Error(string.Format("针对用户推送消息失败，推送内容：{0} 原因：用户未绑定设备", pushmsg.MsgText));
                    return null;
                }
                request.PushType = 4;
                request.DeviceTokens = deviceTokes;
            }
            return request;
        }
        #endregion

    }
}
